package com.chrudgames.stayintouch;

import java.sql.Date;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;


public class Detail extends Activity implements OnClickListener {
	
	private static Context context;
	public String phoneNumbers = "";
    private int mYear;
    private int mMonth;
    private int mDay;

    static final int DATE_DIALOG_ID = 0;

	/** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail);
        
        context = getApplicationContext();
  
        
     getInfo();
     getLast();
      // getCalls();
        
  
    
    
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            
        case R.id.communicate:
        	Intent i4 = new Intent(this, Communicate.class);

        	startActivity(i4);
        	return true;
      	
        case R.id.options:
            	Intent i = new Intent(this, Prefs.class);
               	startActivity(i);
    	
                return true;
            case R.id.upgrade:
            	Intent i3 = new Intent(this, Upgrade.class);
               	startActivity(i3);
                return true;
            case R.id.help:
            	Intent i2 = new Intent(this, Help.class);
               	startActivity(i2);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    
    public void getInfo(){
    	
        
        Bundle b = getIntent().getExtras();
        String lookupKey = b.getString("lookupKey");
    	
     
        
    	Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
    	
    	
    	Cursor c = getContentResolver().query(lookupUri, new String[]{Contacts.DISPLAY_NAME, Contacts.LAST_TIME_CONTACTED, Contacts.HAS_PHONE_NUMBER},null, null, null);
    	try {
    	    c.moveToFirst();
    	    String displayName = c.getString(0);
    	   // Long lastContact = c.getLong(1);
    	    
    	    TextView mTextView = (TextView) findViewById(R.id.tvName);
            mTextView.setText(displayName);
                         
            final EditText et = (EditText)findViewById(R.id.txtMax);
            final String freq = Integer.toString(b.getInt("frequency"));
            et.setText(freq);
           
    	    
            String hasPhone = c.getString(2);
            
          
            
           if (hasPhone.contains("1")) { 
        	   
        
      	      // You know it has a number so now query it like this
            Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY +" = '" + lookupKey + "'", null, null);  
      	      while (phones.moveToNext()) { 
      	        phoneNumbers = phoneNumbers + "'" + phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) + "',";
      	        	         
      	      
      	      } 
      	   phones.close(); 
      	 if(phoneNumbers.length()>1){  phoneNumbers = phoneNumbers.substring(0, phoneNumbers.length() - 1);}
      	 phoneNumbers = phoneNumbers.replaceAll("-", "");
  
      	}
            
            
    	} finally {
    	    c.close();
    	}
    	  
    	
    	
    }
    
    public void getLast(){
		  
    	
    	
    	TextView mTextView = (TextView) findViewById(R.id.tvLast);
        
        Bundle b = getIntent().getExtras();
        String lookupKey = b.getString("lookupKey");
          

        DatabaseHandler db = new DatabaseHandler(this);
        Cursor contact = (Cursor) db.getContactCursor(lookupKey);
        
        while (contact.moveToNext()) { 
       
        	if(contact.getString(2).contentEquals("1800-01-01")){
        		
        		// get the current date
                final Calendar c = Calendar.getInstance();
                mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);
        		
        		mTextView.setText(this.getString(R.string.No_calls_found));
        		
        	}else{
        	
        	mYear = Date.valueOf(contact.getString(2)).getYear() + 1900;	
        	mMonth = java.sql.Date.valueOf(contact.getString(2)).getMonth();
        	mDay = java.sql.Date.valueOf(contact.getString(2)).getDate();
        	 
        
        	
                    mTextView.setText(this.getString(R.string.Last_Contact) + " " + android.text.format.DateFormat.getMediumDateFormat(context).format(java.sql.Date.valueOf(contact.getString(2))));
        	}
             
        }
    	
        contact.close();
        db.close();
    	
    }
    
    
    @Override
    protected void onPause() {
    	super.onPause();
    	
    	 
    }
    
    
       
   
    
    public void deleteContact() {
    	
    	Bundle b = getIntent().getExtras();
        String lookupKey = b.getString("lookupKey");
    	
    	DatabaseHandler db = new DatabaseHandler(this);
    	
    	db.runQuery("delete from contacts where _id='" + lookupKey + "'");
        db.close();
   
        
        finish();
        
    	}
    
    public void updateMax() {
    	
    	final Bundle b = getIntent().getExtras();
        final String lookupKey = b.getString("lookupKey");
    	
        final EditText et = (EditText)findViewById(R.id.txtMax);
   	 	      
        String freq = et.getText().toString();
        
        if(freq.length()<1 || freq.equals("0")){
        	freq="1";
        }
        
    	DatabaseHandler db = new DatabaseHandler(this);
    	
    	db.runQuery("update contacts set frequency = " + freq + " where _id='" + lookupKey + "'");
        db.close();
        
        finish();
        
    	}
 
    
    private void call() {
        try {
        	
        	Bundle b = getIntent().getExtras();
            final String phone = b.getString("phone");
                    	
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + phone));
            startActivity(callIntent);
        } catch (ActivityNotFoundException e) {
       
        }
    }

    /*
    
    private void smsShare() {
    	try{
    	
    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
    		builder.setMessage(this.getString(R.string.This_will_send))
    		       .setCancelable(false)
    		       .setTitle(this.getString(R.string.Please_Confirm))
    		       .setPositiveButton(this.getString(R.string.Sure), new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
    		                smsShareYes();
    		           }
    		       })
    		       .setNegativeButton(this.getString(R.string.No), new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
    		                dialog.cancel();
    		           }
    		       });
    		AlertDialog alert = builder.create();	
    		
    	alert.show();
    	
    	    	
    	}catch(Exception e){
    		
    		alertbox(this.getString(R.string.SMS_Fail), this.getString(R.string.Failed) + e.getMessage());
    		
    	}
    	
    }
    
    
   public void smsShareYes(){
	   Bundle b = getIntent().getExtras();
       final String phone = b.getString("phone");
  	
   	String sent = "android.telephony.SmsManager.STATUS_ON_ICC_SENT";
  	
   	SmsManager sms = SmsManager.getDefault();
   	
   	PendingIntent piSent = PendingIntent.getBroadcast(this, 0,new Intent(sent), 0);
   	
   	sms.sendTextMessage(phone, null, this.getString(R.string.Link_to) + " https://play.google.com/store/apps/details?id=com.chrudgames.stayintouch", piSent, null);

   	alertbox(this.getString(R.string.SMS_Sent), this.getString(R.string.Link_sent_to) + phone);
   }
    
    */
    
    public void showContact() {
    	
    	Bundle b = getIntent().getExtras();
        String lookupKey = b.getString("lookupKey");
    	
      
        
    	Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
         
    Intent intent = new Intent(Intent.ACTION_VIEW);
 
    intent.setData(lookupUri);
    startActivity(intent);

    }
  
    
    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                
    	
    	
    	public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    
    		 
    		
    				DatabaseHandler db = new DatabaseHandler(context);
                    
    				Bundle b = getIntent().getExtras();
    		        String lookupKey = b.getString("lookupKey");
    		        
    		        String month=(monthOfYear+1)+"";
    		        if(month.length()<2){
    		             month="0"+month;   
    		        } 
    		        
    		        
    		        String day=(dayOfMonth)+"";
    		        if(day.length()<2){
    		             day="0"+day;   
    		        }
   				
    		     
    		        
                	db.runQuery("update contacts set last = '" + year + "-" + month + "-" + day + "' where _id='" + lookupKey.toString() + "'");
                	db.close();
                	
                	getLast();

                }
            };
            
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
        	
        	
            return new DatePickerDialog(this,
                        mDateSetListener,
                        mYear, mMonth, mDay);
        }
        return null;
    }
    
    public void onClick(View v) {
    	
    	switch (v.getId()) {
    	
    	case R.id.tvName:
    		showContact();
          	break;
    	
     	case R.id.imgComm:

            
    		Intent i2 = new Intent(this, Communicate.class);

          	startActivity(i2);
          	
          	break;	
          	
    	case R.id.btnCall:
    		call();
    		finish();
          	break;
    	    	
          	
    	case R.id.imgEdit:
    		showDialog(DATE_DIALOG_ID);
          	break;
    	
    	case R.id.tvLast:
    		showDialog(DATE_DIALOG_ID);
          	break;
          	
    	case R.id.btnDelete:
    		deleteContact();
          	break;
    	
    	case R.id.btnSaveDetail:
    		updateMax();
          	break;  	
          	
    	case R.id.btnMore:
    	
    		final Bundle b = getIntent().getExtras();
            final String lookupKey = b.getString("lookupKey");
    		
  	    	Log.d("Number","Deatil: " + lookupKey);
	    	  
            
            //final EditText et = (EditText)findViewById(R.id.txtMax);
            //String freq = et.getText().toString();
            
    		Intent i = new Intent(this, Stats.class);
            Bundle b1 = new Bundle();

            b1.putString("lookupKey", lookupKey);
            //b1.putInt("frequency", intFrequency);

            i.putExtras(b1);
                  	
          	startActivity(i);
          	
          	break;
    	
    	}

     
	          
          
        }

    
    protected void alertbox(String title, String mymessage)
    {
    new AlertDialog.Builder(this)
       .setMessage(mymessage)
       .setTitle(title)
       .setCancelable(true)
       .setNeutralButton(android.R.string.ok,
          new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton){}
          })
       .show();
    }
    
}